import { Injectable, BadRequestException } from '@nestjs/common';
import { UsersService } from '../users/users.service';
import { JwtService } from '@nestjs/jwt';
import { LoginUserDto } from '../users/dto';
import { Relust } from '../utils/relust/relust';
import { ArticleEntity } from '../article/article.entity';
import { createQueryBuilder } from 'typeorm';
import { getManager as getConnectionManager } from 'typeorm';

@Injectable()
export class AuthService {
  constructor(
    private userService: UsersService,
    private jwtService: JwtService,
  ) {}

  async validateUser({ username, password }: LoginUserDto): Promise<any> {
    const user = await this.userService.findOne(username);
    if (user && user.password === password) {
      const { username, email, id } = user;

      console.log(this.jwtService);
      return {
        username,
        email,
        id,
        role: user.role.code,
        authority: user.role.authority,
        token:
          'Bearer ' +
          this.jwtService.sign({
            name: user.username,
            sub: user.id,
            type: user.role.name,
          }),
      };
    }
    throw new BadRequestException(null, '无效用户/密码错误!');

    /*  const user = await this.userService.findOne(username)
                                                                                                                                                            if (user && user.password === pass) {
                                                                                                                                                              const { password, ...result } = user
                                                                                                                                                              return result
                                                                                                                                                            }
                                                                                                                                                            return null*/
  }

  async validateUserAdmin({ username, password }: LoginUserDto): Promise<any> {
    const user = await this.userService.findOne(username);
    if (user && user.password === password) {
      if (user.type !== 'admin') {
        throw new BadRequestException(null, '该用户不是管理员');
      }
      const { username, email, id } = user;
      return {
        username,
        email,
        id,
        token:
          'Bearer ' +
          this.jwtService.sign({
            name: user.username,
            sub: user.id,
            type: user.type,
          }),
      };
    }
    throw new BadRequestException(null, '无效用户/密码错误!');

    /*  const user = await this.userService.findOne(username)
                                                                                                                                                            if (user && user.password === pass) {
                                                                                                                                                              const { password, ...result } = user
                                                                                                                                                              return result
                                                                                                                                                            }
                                                                                                                                                            return null*/
  }

  async reg(user?: any) {
    const userInfo = await this.userService.findOne(user.username);
    console.log(userInfo);
    if (userInfo) {
      throw new BadRequestException(null, '用户存在了');
    } else {
      return this.userService.save(user);
    }
  }


  async init() {

    //const users = await sql.query('SELECT * FROM users');
    const mysql = async (wz:string,data:any[],sjk?) => {
            const sql = await getConnectionManager();
            let ss = data.map(i=>{
                return i[0]}
            ).join(',')
          //  console.log(`select * from role where FIND_IN_SET(id,${ss})`)
            let a = await sql.query(`select * from ${sjk} where FIND_IN_SET(id,'${ss}')`)
           let sqlstr = ''
              data.forEach(item=>{
                if(!a.find(i=> Number(item[0]) === i.id)){
                    sqlstr = sqlstr + `('${item[0]}', '${item[1]}', '${item[2]}', '${item[3]}'),`
                }
            })
        sqlstr = sqlstr.substr(0, sqlstr.length - 1);
        sqlstr && await sql.query(`insert INTO ${wz} VALUES ${sqlstr}`);

    }


    //初始化数据库

      mysql("`role` (`id`, `name`, `desc`, `code`)",[['1', 'admin', '管理员', 'admin'],['2', 'ptyh', '普通用户已', 'ptyh'],['3', 'fyhh', '发布用户', 'fyhh'],['4', 'vip', 'vip用户', 'vip']],'role')


      mysql("`authority` (`id`, `name`, `desc`, `code`)",[['1', '文章发布', '文章发布功能', 'addtext'],['2', '评论发布', '评论发布功能', 'comment/list'],['3', '网盘', '网盘功能', 'wangpan']],'authority')


      const sql = await getConnectionManager();

      let ac = await sql.query(`select * from users where FIND_IN_SET(username,'admin')`)
      //添加基础用户
      if(!ac.length){
          await sql.query(
              "REPLACE INTO `users` (`username`, `password`, `email`, `cgdate`,`type`,`roleId`) VALUES ('admin', '111111', '123@qq.com', '2020-04-10 01:22:07','admin','1')",
          );
      }

 //2
    return '数据库初始化成功！';
  }
}
